import React, { ReactNode, useState, useEffect } from 'react';
import { Layout, Menu, Dropdown, Avatar } from 'antd';
import type { MenuProps } from 'antd';
import Link from 'next/link';
import { useRouter } from 'next/router';
import { routes } from '@/config/router';
<<<<<<< HEAD
import HeaderComponent from '@/components/header';
=======
import { UserOutlined, LogoutOutlined } from '@ant-design/icons';

>>>>>>> a805099c2d528faac82e7b798acb7cde659bfa9c
const { Header, Content, Sider } = Layout;
const { SubMenu } = Menu;

interface RouteItem {
  path: string;
  label: string;
  key?: string;
  icon?: React.ComponentType;
  component?: string;
  children?: RouteItem[];
}

function renderMenuItem(item: RouteItem) {
  if (item.children) {
    return (
      <SubMenu key={item.key} icon={item.icon && <item.icon />} title={item.label}>
        {item.children.map(child => renderMenuItem(child))}
      </SubMenu>
    );
  }
  return (
    <Menu.Item key={item.path} icon={item.icon && <item.icon />} onChange={()=>{
        console.log('item.path', item.path);
    }}>
      <Link href={item.path} legacyBehavior>
        <a>{item.label}</a>
      </Link>
    </Menu.Item>
  );
}

interface MainLayoutProps {
  children: ReactNode;
}

function convertToMenuItems(routes: RouteItem[]): MenuProps['items'] {
  return routes.map(route => {
    if (route.children) {
      return {
        key: route.key || route.path,
        icon: route.icon && <route.icon />,
        label: route.label,
        children: convertToMenuItems(route.children)
      };
    }
    return {
      key: route.path,
      icon: route.icon && <route.icon />,
      label: (
        <Link href={route.path} legacyBehavior>
          <a>{route.label}</a>
        </Link>
      )
    };
  });
}

export default function MainLayout({ children }: MainLayoutProps) {
  const router = useRouter();
  const [selectedKeys, setSelectedKeys] = useState<string[]>([]);
  const [openKeys, setOpenKeys] = useState<string[]>([]);
  const [username, setUsername] = useState('用户名'); // 假设用户名，实际应从用户状态或 API 获取

  useEffect(() => {
    const pathName = router.pathname;
    const openKeys: string[] = [];
    const selectedKeys: string[] = [];

    const findKeys = (items: RouteItem[], parentPath = ''): boolean => {
      for (const item of items) {

        if (pathName === item.path || item.path.startsWith(pathName) || pathName.startsWith(`${item.path}/`)) {
          selectedKeys.push(item.path);
          if (parentPath) {
          
            openKeys.push(parentPath);
          }
          if (item.children) {
            findKeys(item.children, item.path);
          }
          return true;
        }
      }
      return false;
    };

    findKeys(routes);
    setSelectedKeys(selectedKeys);
    setOpenKeys(openKeys);
  }, [router.pathname]);

  const handleOpenChange = (keys: string[]) => {
    console.log('keys', keys);
    setOpenKeys(keys);
  };

  const handleLogout = () => {
    // 实现登出逻辑
    console.log('用户登出');
  };

  const userMenuItems: MenuProps['items'] = [
    {
      key: 'logout',
      icon: <LogoutOutlined />,
      label: '退出登录',
      onClick: handleLogout,
    },
  ];

  return (
    <Layout style={{ minHeight: '100vh' }}>
<<<<<<< HEAD
      <Header style={{ background: '#001529'}}>
        <HeaderComponent />
=======
      <Header style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div className="logo" style={{ color: 'white', fontSize: '20px' }}>
          Logo
        </div>
        <Dropdown menu={{ items: userMenuItems }} placement="bottomRight">
          <div style={{ color: 'white', cursor: 'pointer',display:'flex',alignItems:'center' }}>
            <Avatar icon={<UserOutlined />} style={{ marginRight: '8px' }} />
            {username}
          </div>
        </Dropdown>
>>>>>>> a805099c2d528faac82e7b798acb7cde659bfa9c
      </Header>
      <Layout>
        <Sider width={200}>
          <Menu
            mode="inline"
            selectedKeys={selectedKeys}
            openKeys={openKeys}
            style={{ height: '100%', borderRight: 0 }}
            onOpenChange={handleOpenChange}
            items={convertToMenuItems(routes)}
          />
        </Sider>
        <Layout style={{ padding: '0 24px 24px' }}>
          <Content
            style={{
              padding: 24,
              margin: 0,
              minHeight: 280,
            }}
          >
            {children}
          </Content>
        </Layout>
      </Layout>
    </Layout>
  );
}
